<?php

namespace app\admin\controller\department;

use app\admin\model\AuthGroupAccess;
use app\admin\model\department\Department as DepartmentModel;
use app\common\controller\Backend;
use app\common\library\Auth;
use fast\Random;
use think\Db;
use fast\Tree;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Article extends Backend
{

    protected $relationSearch = true;
    protected $noNeedRight = ["setAuth", "cancelAuth"];

    /**
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\department\Article;
        //类别
        $typeList = \app\admin\model\department\Type::all();
        $this->view->assign("typeList", json_encode($typeList, true));
        //职务
        $positionList = \app\admin\model\department\Position::all();
        $this->view->assign("positionList", json_encode($positionList, true));
        //组别
        $groupingList = \app\admin\model\department\Grouping::all();
        $this->view->assign("groupingList", json_encode($groupingList, true));
        //部门
        $this->tree = Tree::instance();
        $this->tree->init(DepartmentModel::allDepartment(), 'parent_id');
        $departmentList = $this->tree->getTreeList($this->tree->getTreeArrayPname(0), 'name');
        $departmentList = collection($departmentList)->toArray();
        $this->view->assign("departmentList", $departmentList);

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $wheres = [];
            $groupIds = $this->auth->getGroupIds($this->auth->id);
            //如果不是超级管理员则按照小组权限查看
            if (!in_array("1", $groupIds)) {
//                $model = new \app\admin\model\Admin;
//                $row = $model->get($this->auth->id);
//                if (empty($row['grouping_id'])) {
//                    $result = array("total" => 0, "rows" => []);
//                    return json($result);
//                }
//                $wheres['article.grouping_id'] = ["in", $row['grouping_id']];
                $this->_getArticleIds($wheres);
                if (empty($wheres)) {
                    $result = array("total" => 0, "rows" => []);
                    return json($result);
                }
            }

            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['department_id'])) {
                $departmentId = $filterArr['department_id'];
                $filterArr = array_diff_key($filterArr, ['department_id' => '']);
                $departmentIds = $this->tree->getChildrenIds($departmentId, true);
                $wheres['article.department_id'] = ["in", $departmentIds];
            }
            $this->request->get(['filter' => json_encode($filterArr)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['createuser', 'grouping', "department", "position", "type"])
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->paginate($limit);
            
            foreach ($list as $k => $v) {
                $userAuth = $this->_checkUserAuth($v->id);
                $v['selfIsAuth'] = 0;
                if ($userAuth) {
                    $v['selfIsAuth'] = 1;
                }
                $departmentList = $this->tree->getParentsIds($v['department_id'], true);
                $departmentIds = DepartmentModel::whereIn('id', $departmentList)->order("id asc")->column("name");
                $v['department_name'] = implode("", $departmentIds);
                $v->hidden(['createuser.password', 'createuser.salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    private function _getArticleIds(&$wheres)
    {
        $ids = $this->model->where(['create_uid' => $this->auth->id])->column("id");
        //小组
//        $model = new \app\admin\model\Admin;
//        $row = $model->get($this->auth->id);
//        if (!empty($row['grouping_id'])) {
//            $groupingIds = $this->model->where(['grouping_id' => ["in", $row['grouping_id']]])->column("id");
//            $ids = array_merge($groupingIds, $ids);
//        }
        $model = new \app\admin\model\department\ArticleUser;
        $bandUsers = $model->where(['user_id' => $this->auth->id])->column("article_id");
        if (!empty($bandUsers)) {
            $ids = array_merge($bandUsers, $ids);
        }
        $ids = array_unique($ids);
        if (!empty($ids)) {
            $wheres["article.id"] = ["in", $ids];
        }
    }

    public function edit($ids = null)
    {
        //编辑权限
        $row = $this->model->get($ids);
        if (empty($row)) {
            $this->error("未找到该条数据");
        }
        if ($this->request->isAjax()) {
            if ($row->publish) {
                $this->error("已发布状态禁止修改");
            }
        }
        $logContent = "课题名称：" . $row->title;
        \app\admin\model\AdminLog::record('编辑课题', $logContent);

        $model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $ids,
            "user_id" => $this->auth->id,
            "is_auth" => 1
        ];
        $exits = $model->where($wheres)->find();
        if ($row->create_uid != $this->auth->id && empty($exits)) {
            echo "暂无编辑权限";die;
        }

        $wheres = [
            "article_id" => $ids
        ];
        $userIds = $model->where($wheres)->column("user_id");
        $users= \app\admin\model\Admin::where(["id" => ['in', $userIds]])->field("id,nickname")->select();
        foreach ($users as &$val) {
            $val['id'] = $val['nickname'];
        }
        $this->view->assign("userList", json_encode($users, true));

        return parent::edit($ids);
    }

    public function del($ids = null)
    {
        $model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $ids,
            "user_id" => $this->auth->id,
            "is_auth" => 1
        ];
        $exits = $model->where($wheres)->find();
        if (empty($exits)) {
            $this->error("暂无删除权限");
        }
        parent::del($ids);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['author'] = $this->auth->nickname;
            $params['first_author'] = $this->auth->nickname;
            $logContent = "课题名称：" . $params['title'];
            \app\admin\model\AdminLog::record('新增课题', $logContent);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    //查看详情
    public function detail($ids = null)
    {
        $row = $this->model
            ->with(['createuser', 'grouping', "department", "position", "type"])
            ->where(['article.id' => $ids])
            ->find();
        if (empty($row)) {
            $this->error("未找到该数据");
        }
		$row->view_num += 1;
		$row->save();
		
        $logContent = "课题名称：" . $row->title;
        \app\admin\model\AdminLog::record('查看课题详情', $logContent);
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }

    //已绑定的用户
    public function articleuser($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $selfIsAuth = 0;
        if ($row->create_uid == $this->auth->id) {
            $selfIsAuth = 1;
        }

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
//            $this->dadminModel = new \app\admin\model\department\Admin;
//            $department_id = $this->dadminModel->where(["admin_id" => $this->auth->id, ])->order("organise_id asc")->value("organise_id");
//            $admin_ids = $this->dadminModel->where('department_id', 'in', $department_id)->column('admin_id');
//            $filter_w['id'] = ['neq', $row->create_uid];
            $wheres = [];
            $groupAuthId = AuthGroupAccess::where(["uid" => $this->auth->id, "group_id" => 1])->find();
            if (empty($groupAuthId)) {
                $wheres = [
                    "auth_admin.id" => ["neq", 1]
                ];
            }
            $filter = $this->request->request('filter');
            $filterArr = (array)json_decode($filter, true);
            if (isset($filterArr['department_id'])) {
                $departmentId = $filterArr['department_id'];
                $filterArr = array_diff_key($filterArr, ['department_id' => '']);
                $departmentIds = $this->tree->getChildrenIds($departmentId, true);
                $wheres['department_id'] = ["in", $departmentIds];
            }
            $this->request->get(['filter' => json_encode($filterArr)]);

            $this->model = new \app\admin\model\department\AuthAdmin();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($wheres)
//                ->where($filter_w)
                ->order($sort, $order)
                ->fetchSql(false)
                ->count();
            $list = $this->model
                ->with(['department', 'position'])
//                ->with(['groups.getGroup'])
//                ->where($filter_w)
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->fetchSql(false)
                ->select();
            $model = new \app\admin\model\department\ArticleUser;
            $wheres = [
                "article_id" => $row->id
            ];
            foreach ($list as &$value) {
                $wheres["user_id"] = $value->id;
                $exits = $model->where($wheres)->find();
                $value['is_band'] = $exits ? 1 : 0;
                if (!empty($exits)) {
                    $value["is_auth"] = $exits->is_auth;
                } else {
                    $value["is_auth"] = 0;
                }


                $departmentList = $this->tree->getParents($value['department_id'], false);
				//halt($departmentList);
                $str = '';
                foreach ($departmentList as $k => &$v) {
                    $temp['name']=str_replace("&nbsp;", ",", strip_tags($v['name'])); //过滤空格
                    $str = $temp['name'] . ",";
                }
                $value['department_name'] = $str .= ($value['department']['name'] ?? '');
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assign("ids", $ids);
        $this->assignConfig("ids", $ids);
        $this->assignConfig("selfIsAuth", $selfIsAuth);
        return $this->view->fetch();
    }

    //已绑定的用户
    public function banduser($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $this->model = new \app\admin\model\department\ArticleUser();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = [
                "article_id" => $row->id,
                "user_id" => ["neq", 1]
            ];
            $total = $this->model
                ->with(['user'])
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($wheres)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->fetchSql(false)
                ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $userAuth = $this->_checkUserAuth($row->id);
        $this->assignConfig("ids", $ids);
        $this->assignConfig("selfIsAuth", $userAuth);
        return $this->view->fetch();
    }

    //绑定操作
    public function banded($ids = null, $article_id = null)
    {
        $article = $this->model->get($article_id);
        if (!$article) {
            $this->error(__('数据错误1'));
        }
        if ($article->publish) {
            $this->error("已发布状态禁止修改");
        }
        $this->model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $article->id,
            "user_id" => $ids
        ];
        $exits = $this->model->where($wheres)->find();
        if (!empty($exits)) {
            $this->error(__('已存在绑定关系，请确认'));
        }
        $data = $wheres;
        $this->model->save($data);
        $this->model->weigh = $this->model->id;
        $this->model->save();

        $this->updateAuthor($article->id, 1);
        $this->success();
    }

    //取消绑定操作
    public function unband($ids = null, $article_id = null)
    {
        $article = $this->model->get($article_id);
        if (!$article) {
            $this->error(__('数据错误1'));
        }
        if ($article->publish) {
            $this->error("已发布状态禁止修改");
        }
        $this->model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $article->id,
            "user_id" => ["in", $ids]
        ];
        $list = $this->model->where($wheres)->select();
        if (empty($list)) {
            $this->error(__('不存在绑定关系，请确认'));
        }
        foreach ($list as $exits) {
            $exits->delete();
        }

        $this->updateAuthor($article->id);
        $this->success();
    }

    //设置为管理员操作
    public function setAuth($ids = null, $article_id = null)
    {
        $article = $this->model->get($article_id);
        if (!$article) {
            $this->error(__('数据错误1'));
        }
        if ($article->publish) {
            $this->error("已发布状态禁止修改");
        }
        $this->model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $article->id,
            "user_id" => $ids
        ];
        $row = $this->model->where($wheres)->find();
        if (empty($row)) {
            $row = new \app\admin\model\department\ArticleUser;
            $row->article_id = $article->id;
            $row->user_id = $ids;
        } else if ($row->is_auth == 1) {
            $this->error(__('已是该项目的管理员，请确认'));
        }
        $row->is_auth = 1;
        $row->save();
        $this->success();
    }

    //取消管理员操作
    public function cancelAuth($ids = null, $article_id = null)
    {
        $article = $this->model->get($article_id);
        if (!$article) {
            $this->error(__('数据错误1'));
        }
        if ($article->publish) {
            $this->error("已发布状态禁止修改");
        }
        $this->model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $article->id,
            "user_id" => $ids
        ];
        $row = $this->model->where($wheres)->find();
        if (empty($row)) {
            $this->error(__('不存在绑定关系，请确认'));
        }
        $row->is_auth = 0;
        $row->save();
        $this->success();
    }

    //发布
    public function publish($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            if ($row->publish == 1) {
                $this->error(__('该作品已处于发布状态'));
            }
            $this->model = new \app\admin\model\department\ArticlePublish;
            $allData = [];
            $params = $this->request->param();
            if (!empty($params['department'])) {
                $ids = explode(",", $params['department']);
                $departmentIds = $this->_getDepartmentIds($ids);
                foreach ($departmentIds as $val) {
                    $allData[] = array(
                        "type" => 1,
                        "article_id" => $row->id,
                        "with_id" => $val
                    );
                }
            }
            //职务
            if (!empty($params['position'])) {
                $ids = explode(",", $params['position']);
                foreach ($ids as $val) {
                    $allData[] = array(
                        "type" => 2,
                        "article_id" => $row->id,
                        "with_id" => $val
                    );
                }
            }
            //类别
            if (!empty($params['type'])) {
                $ids = explode(",", $params['type']);
                $typeIds = $this->_getTypeIds($ids);
                foreach ($typeIds as $val) {
                    $allData[] = array(
                        "type" => 3,
                        "article_id" => $row->id,
                        "with_id" => $val
                    );
                }
            }
            if (!empty($allData)) {
                $this->model->saveAll($allData);
            }

            $row->publish = 1;
            $row->publish_time = time();
            $row->save();
            $logContent = "课题名称：" . $row['title'];
            \app\admin\model\AdminLog::record('发布课题', $logContent);
            $this->success();
        }
        $this->assign("ids", $ids);
        return $this->view->fetch();
    }
    private function _getDepartmentIds($department)
    {
        $ids = [];
        foreach ($department as $val) {
            $departmentIds = DepartmentModel::getChildrenIds($val, true);
            $ids = array_merge($departmentIds, $ids);
        }
        return array_unique($ids);
    }
    private function _getTypeIds($type)
    {
        $ids = [];
        foreach ($type as $val) {
            $typeIds = \app\admin\model\department\Type::getChildrenIds($val, true);
            $ids = array_merge($typeIds, $ids);
        }
        return array_unique($ids);
    }

    //下架
    public function offshelf($ids = null)
    {
//        $article_id = $this->request->param('ids', 0);
        $list = \app\admin\model\department\Article::whereIn('id', $ids)->select();
        if (empty($list)) {
            $this->error("数据错误");
        }
        $title = [];
        foreach ($list as $row) {
            $this->model = new \app\admin\model\department\ArticlePublish;
            $where = array(
                "article_id" => $row->id,
            );
            $this->model->where($where)->delete();

            $row->publish = 0;
            $row->save();
            $title[] = $row['title'];
        }

        $logContent = "课题名称：" . implode(",", $title);
        if (mb_strlen($logContent) > 200) {
            $logContent = mb_substr($logContent, 0, 200);
        }
        \app\admin\model\AdminLog::record('成品中批量下架课题', $logContent);
        $this->success();
    }


    //获取分组里的用户
    public function getGroupingUsers($ids = null)
    {
        $row = $this->model->get($ids);
        if (empty($row)) {
            $this->error("请先绑定项目所在分组");
        }
        $model = new \app\admin\model\Admin;
        $where[] = ['exp',Db::raw("FIND_IN_SET('{$row["grouping_id"]}', grouping_id)")];
        $users = $model->where($where)->field("id,nickname")->select();
        foreach ($users as &$val) {
            $val['id'] = $val['nickname'];
        }
        return json(['list' => $users, 'total' => count($users)]);
    }

    //检查用户对该作品是否管理员
    private function _checkUserAuth($ids): bool
    {
        $row = $this->model->get($ids);
        if (empty($row)) {
            $this->error("未找到该条数据");
        }

        $model = new \app\admin\model\department\ArticleUser;
        $wheres = [
            "article_id" => $row->id,
            "user_id" => $this->auth->id,
            "is_auth" => 1
        ];
        $exits = $model->where($wheres)->find();
        if ($row->create_uid != $this->auth->id && empty($exits)) {
            return false;
        }
        return true;
    }

    /**
     * 成员排序
     */
    public function weigh()
    {
        $article_id = $this->request->param("article_id");
        $row = \app\admin\model\department\Article::where(['id' => $article_id])->find();
        if ($row->publish) {
            $this->error("已发布状态禁止修改");
        }
        //排序的数组
        $ids = $this->request->post("ids");
        //拖动的记录ID
        $changeid = $this->request->post("changeid");
        //操作字段
        $field = $this->request->post("field");
        //操作的数据表
        $table = $this->request->post("table");
        if (!Validate::is($table, "alphaDash")) {
            $this->error();
        }
        //主键
        $pk = $this->request->post("pk");
        //排序的方式
        $orderway = strtolower($this->request->post("orderway", ""));
        $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
        $sour = $weighdata = [];
        $ids = explode(',', $ids);
        $prikey = $pk && preg_match("/^[a-z0-9\-_]+$/i", $pk) ? $pk : (Db::name($table)->getPk() ?: 'id');
        $pid = $this->request->post("pid", "");
        //限制更新的字段
        $field = in_array($field, ['weigh']) ? $field : 'weigh';

        // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
        if ($pid !== '') {
            $hasids = [];
            $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
            foreach ($list as $k => $v) {
                $hasids[] = $v[$prikey];
            }
            $ids = array_values(array_intersect($ids, $hasids));
        }

        $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
        foreach ($list as $k => $v) {
            $sour[] = $v[$prikey];
            $weighdata[$v[$prikey]] = $v[$field];
        }
        $position = array_search($changeid, $ids);
        $desc_id = isset($sour[$position]) ? $sour[$position] : end($sour);    //移动到目标的ID值,取出所处改变前位置的值
        $sour_id = $changeid;
        $weighids = array();
        $temp = array_values(array_diff_assoc($ids, $sour));
        foreach ($temp as $m => $n) {
            if ($n == $sour_id) {
                $offset = $desc_id;
            } else {
                if ($sour_id == $temp[0]) {
                    $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
                } else {
                    $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
                }
            }
            if (!isset($weighdata[$offset])) {
                continue;
            }
            $weighids[$n] = $weighdata[$offset];
            Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
        }

        $this->updateAuthor($article_id);
        $this->success();
    }

    private function updateAuthor($article_id, $type = 0)
    {
        $model = new \app\admin\model\department\ArticleUser;
        $where = [
            'article_id' => $article_id,
            'user_id' => ['neq', 1]
        ];
        $nicknames = $model->with("user")->where($where)->order("weigh desc")->column("nickname");
        $map = [
            "update_time" => time()
        ];
//        unset($nicknames[0]);
        if (!empty($nicknames) && !$type) {
            $map['first_author'] = $nicknames[0];
        }
        if (!empty($nicknames)) {
            $map['author'] = implode(",", $nicknames);
        }
        \app\admin\model\department\Article::where(['id' => $article_id])->update($map);
    }


    //导入项目成员
    public function articleuserexcel($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->publish) {
            $this->error("已发布状态禁止修改");
        }
        if ($this->request->isPost()) {
            ini_set('memory_limit', '-1'); //设置为不限制
            set_time_limit(0);  //设置为不限制

            $fileName = input('pdf');
            $fileName = str_replace($_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"], '', $fileName);
            $file = $_SERVER ["DOCUMENT_ROOT"] . $fileName;
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);  //过滤excel中的特殊字符
            $PHPExcel = $reader->load($file);
            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $data = [];

            for ($row = 2; $row <= $highestRow; $row++) { //行号从1开始
                for ($column = 'A'; $column <= $highestColumn; $column++) { //列数是以A列开始
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $data[$row][$column] = $sheet->getCell($column . $row)->getValue();
                    }
                }
            }
//            halt($data);
            $model = new \app\admin\model\department\ArticleUser;
            Db::startTrans();
            try {
                $dataArr = [];
                $j = 2;
                foreach ($data as $k => $v) {
                    if (empty($v['A'])) {
                        $this->error("第【{$j}】行的用户姓名未填，请修改后重试");
                    }
                    if (!isset($v['B'])) {
                        $v['B'] = 0;
                    }
                    if (empty($v['C'])) {
                        $v['C'] = 100;
                    }
                    $v['A'] = trim($v['A']);
                    $exits = \app\admin\model\Admin::where('nickname', trim($v['A']))->value('id');
                    if (empty($exits)) {
                        $this->error("第【{$j}】行的用户姓名不存在，请修改后重试");
                    }
                    $dataArr[$v['A']] = $exits;
                    $j++;
                }
                $res = [];
                $time = time();
                foreach ($data as $k => $v) {
                    $uid = $dataArr[$v['A']];
                    $isAuth = $v['B'] == 2 ? 1 : 0;
                    $temp = [
                        "user_id" => $uid,
                        "article_id" => $ids,
                        "is_auth" => $isAuth,
                        "weigh" => $v['C'],
                        "create_time" => $time,
                    ];

                    $res[] = $temp;
                }
                if (!empty($res)) {
                    $model->saveAll($res);
                    $this->updateAuthor($ids);
                }
                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $doc = "/template/excel/小组成员导入模板.xlsx";
        $this->view->assign("doc", $doc);
        $this->view->assign("ids", $row->id);
        return $this->view->fetch();
    }

    public function excel()
    {
        if ($this->request->isPost()) {
            ini_set('memory_limit', '-1'); //设置为不限制
            set_time_limit(0);  //设置为不限制

            $fileName = input('pdf');
            $fileName = str_replace($_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"], '', $fileName);
            $file = $_SERVER ["DOCUMENT_ROOT"] . $fileName;
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);  //过滤excel中的特殊字符
            $PHPExcel = $reader->load($file);
            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $data = [];

            for ($row = 2; $row <= $highestRow; $row++) { //行号从1开始
                for ($column = 'A'; $column <= $highestColumn; $column++) { //列数是以A列开始
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $data[$row][$column] = $sheet->getCell($column . $row)->getValue();
                    }
                }
//                if (!isset($data[$row]['B'])) unset($data[$row]);
            }
            Db::startTrans();
            try {
                $dataArr = [];
                $j = 2;
                foreach ($data as $k => $v) {
                    if (empty($v['A'])) {
                        $this->error("第【{$j}】行的名称未填，请修改后重试");
                    }
                    if (empty($v['C'])) {
                        $this->error("第【{$j}】行的内容未填，请修改后重试");
                    }
                    $exits = $this->model->where('title', $v['A'])->value('id');
                    if (!empty($exits)) {
                        $this->error("第【{$j}】行的名称已存在，请修改后重试");
                    }
                    $j++;
                }
                $res = [];
                foreach ($data as $k => $v) {
                    $first_author = isset($v['G']) ? trim($v['G']) : '';
                    $author = isset($v['H']) ? trim($v['H']) : '';
                    $temp = [
                        "create_uid" => 1,
                        "title" => $v['A'],
                        "introduction" => $v['B'] ?? '',
                        "content" => $v['C'],
                        "source" => $v['D'] ?? '',
                        "direction" => $v['E'] ?? '',
                        "territory" => trim($v['F']) ?? '',
                        "first_author" => $first_author,
                        "author" => $author,
//                        "department_id" => $this->_getDepartmentId($v['I']),
//                        "position_id" => $this->_getPositionId($v['J']),
                        "is_public" => 1,
                        "publish" => 1,
                        "publish_time" => time(),
//                        "grouping_id" => $this->_getGroupingId($v['H']),
//                        "type_id" => $this->_getTypeId($v['J']),
                    ];
                    if (!empty($v['I'])) {
                        $temp['department_id'] = $this->_getDepartmentId($v['I']);
                    }
//                    if (!empty($v['J'])) {
//                        $temp['position_id'] = $this->_getDepartmentId($v['J']);
//                    }
                    $res[] = $temp;
                }
                if (!empty($res)) {
                    $this->model->saveAll($res);
                }
                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $doc = "/template/excel/成品导入模板.xlsx";
        $this->view->assign("doc", $doc);
        return $this->view->fetch();
    }
    //获取部门id
    private function _getDepartmentId($name)
    {
        $departmentArr = explode("-", $name);
        $model = new \app\admin\model\department\Department;
        $where = [];
        $id = null;
        foreach ($departmentArr as $value) {
            $where['name'] = $value;
            $id = $model->where($where)->value("id");
            if (empty($id)) {
                break;
            }
            $where['parent_id'] = $id;
        }
        return $id;
    }
    //获取职位ID
    private function _getPositionId($name)
    {
        if (empty($name)) return null;
        $model = new \app\admin\model\department\Position;
        $id = $model->where("name", $name)->value("id");
        return $id;
    }

}
